Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Google Medium
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Arithmetic Slices

Problem Statement

Given an integer array nums, return the number of arithmetic subarrays of nums.

If any integer array consists of at least three elements and if the difference between any two consecutive elements is the same, it is called arithmetic.

A subarray is a contiguous subsequence of the array.

Examples

Example 1:

  • Input: [1, 3, 5, 7, 9, 10, 11]
  • Expected Output: 7
  • Justification: The segments that form arithmetic sequences are [1, 3, 5], [3, 5, 7], [5, 7, 9], [1, 3, 5, 7], [3, 5, 7, 9], [1, 3, 5, 7, 9], and [9, 10, 11]. Each of these segments has a constant difference of 2 between consecutive elements.

Example 2:

  • Input: [7, 7, 7, 7]
  • Expected Output: 3
  • Justification: The qualifying segments are [7, 7, 7], [7, 7, 7, 7] (considering the first three and then all four elements), and the last three elements [7, 7, 7]. Each segment has a constant difference of 0 between its elements.

Example 3:

  • Input: [1, 2, 4, 6, 8]
  • Expected Output: 3
  • Justification: Only three segments [2,4,6], [4, 6, 8] and [2, 4, 6, 8] form arithmetic sequences with a constant difference of 2.

Solution

To solve this problem, we will iterate through the array while keeping track of the current arithmetic sequence's length. The approach hinges on understanding that for any arithmetic sequence with more than three elements, it inherently contains smaller arithmetic sequences. For instance, a sequence of four elements contains three smaller sequences. Thus, we calculate the total count of sequences as we identify them.

The rationale behind this approach is its efficiency and simplicity; it avoids unnecessary nested iterations, focusing instead on leveraging the arithmetic property of contiguous subarrays. This method is expected to work well because it directly counts sequences without explicitly enumerating all possible subarrays, thus optimizing both time and space complexity.

Step-by-Step Algorithm

  1. Initialization: Start by checking if the input array nums has fewer than 3 elements. If yes, return 0 immediately since at least three elements are needed to form an arithmetic slice.

  2. Setup Counters: Initialize two counters: count to store the total number of arithmetic slices found, and consecutive to track the length of the current consecutive arithmetic slice sequence.

  3. Iterate Through Array: Begin iterating through the array starting from the third element (index 2), as the first two elements are used for initial comparison.

  4. Check Arithmetic Sequence: For each element at index i, check if the difference between the current element and the previous one (nums[i] - nums[i-1]) is the same as the difference between the previous element and the one before it (nums[i-1] - nums[i-2]). This checks if the current set of three elements forms part of an arithmetic sequence.

  5. Update Counters: If the current set of elements continues an arithmetic sequence, increment the consecutive counter by 1. Then, add the value of consecutive to count. This step accounts for the number of new arithmetic slices that include the current element.

  6. Reset consecutive if Needed: If the current set of elements does not continue an arithmetic sequence, reset the consecutive counter to 0. This prepares it for the next sequence of arithmetic slices.

  7. Complete Iteration and Return: Continue steps 4 through 6 for each element in the array. After completing the iteration, return the total count of arithmetic slices found.

Algorithm Walkthrough

Let's consider the Input: nums = [1, 3, 5, 7, 9, 10, 11]

  1. Initialization: The input array has more than 3 elements, so we proceed.

  2. Setup Counters: Initialize count = 0 and consecutive = 0.

  3. First Iteration (i = 2, Element = 5):

    • Calculate differences: 5 - 3 = 2 and 3 - 1 = 2. They are equal.
    • Increment consecutive to 1.
    • Add consecutive to count (count = 1).
  4. Second Iteration (i = 3, Element = 7):

    • Differences: 7 - 5 = 2 and 5 - 3 = 2. Still equal.
    • Increment consecutive to 2.
    • Add consecutive to count (count = 3).
  5. Third Iteration (i = 4, Element = 9):

    • Differences: 9 - 7 = 2 and 7 - 5 = 2. Equal again.
    • Increment consecutive to 3.
    • Add consecutive to count (count = 6).
  6. Fourth Iteration (i = 5, Element = 10):

    • Differences: 10 - 9 = 1 and 9 - 7 = 2. Not equal.
    • Reset consecutive to 0.
  7. Fifth Iteration (i = 6, Element = 11):

    • Differences: 11 - 10 = 1 and 10 - 9 = 1. Equal.
    • Increment consecutive to 1.
    • Add consecutive to count (count = 7).
  8. Completion: After completing the iteration, we find that the total count of arithmetic slices is 7.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the number of elements in the input array nums. This is because the solution involves a single pass through the array to count arithmetic slices, with constant time operations performed for each element.

Space Complexity

The space complexity for the algorithm is . This is because the amount of extra space used does not depend on the size of the input array.

Arithmetic Slices (medium)
Unique Length-3 Palindromic Subsequences (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity